package com.mach.platform.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.mach.platform.domain.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author Administrator
 * @Name
 * @Description: 登录相关
 * @date 2018/4/20 0020   11:49
 */
@Api(tags = { "登录相关接口" })
@Controller
public class LoginCtrl {

	@Autowired
	private Producer producer;

	/**
	 * 图片验证码
	 *
	 * @return
	 */
	@ApiOperation(value = "请求验证码", produces = "arraybuffer",notes = "返回二进制流,前端用arraybuffer接收response内容")
	@RequestMapping(value = "/kaptcha.jpg", method = RequestMethod.GET)
	public void requestForVerifyCode (HttpServletRequest request, HttpServletResponse response) {

		HttpSession session = request.getSession();
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		String text = producer.createText();
		text = "0";//TODO debug close kap
		session.setAttribute(Constants.KAPTCHA_SESSION_KEY, text);

		BufferedImage bufferedImage = producer.createImage(text);

		try {
			ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 虚拟 登录请求----请求整整方法不在这里---在springSecurity中。 这里为了显示给 接口 显示
	 * @param username 用户名
	 * @param password  登录密码
	 * @param verification  验证码
	 * @return
	 */
	@ApiOperation(value = "登录请求",notes = " post请求------需先请求验证码:  参数用 x-www-form-urlencoded 方式发送",produces = "application/json")
	@PostMapping("/login")
	public Response doLogin (@RequestParam("username") String username, @RequestParam("password") String password,
			@RequestParam("verification") String verification) {

		return Response.ok();

	}

}
